import { _decorator, Component, Node, Sprite, resources, SpriteFrame, Label, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('player')
export class player extends Component {
    @property(Node)
    player: Node = null
    @property(Node)
    ai: Node = null

    imgs: SpriteFrame[] = []
    count: number = 0
    callback: any = null

    start() {
        resources.loadDir('img', SpriteFrame, (err: any, assets) => {
            this.imgs = assets.sort((a: SpriteFrame, b: SpriteFrame) =>
                Number(a.name.slice(0, 1)) - Number(b.name.slice(0, 1)))
        });
    }
    onPlayBtnCLick() {
        const uiTransform = this.getComponentInChildren(UITransform);
        const btnLabel = this.getComponentInChildren(Label)
        const playerSprite = this.player.getComponent(Sprite);
        const aiSprite = this.ai.getComponent(Sprite);
        uiTransform.width = 200
        btnLabel.string = '决一胜负吧！';
        
        const playerRandom = Math.floor(Math.random()*3)
        const aiRandom = Math.floor(Math.random()*3)

        // 以秒为单位的时间间隔
        let interval = 0.1;
        // 重复次数
        let repeat = 5;
        this.count = 0;
        this.callback = () => {
            // 在第六次执行回调时取消这个计时器
            if (this.count === repeat) {
                this.gameover(playerRandom, aiRandom)
                this.unschedule(this.callback);
                return
            }

            playerSprite.spriteFrame = this.imgs[Math.floor(Math.random()*3)]
            aiSprite.spriteFrame = this.imgs[Math.floor(Math.random()*3)]
            this.count++;
        }
        this.schedule(this.callback, interval);

    }
    gameover(playerRandom: number, aiRandom: number) {
        const btnLabel = this.getComponentInChildren(Label)
        const uiTransform = this.getComponentInChildren(UITransform);
        uiTransform.width = 350
        const playerSprite = this.player.getComponent(Sprite);
        const aiSprite = this.ai.getComponent(Sprite);
        
        if (playerRandom - aiRandom === -1 || playerRandom - aiRandom === 2) {
            btnLabel.string = '恭喜！你赢了！再来一次？';
        } else if (playerRandom - aiRandom === 0) {
            btnLabel.string = '咦？！平手！再来一次？';
        } else {
            btnLabel.string = '遗憾遗憾！你输了！再来一次？';
        }
        playerSprite.spriteFrame = this.imgs[playerRandom]
        aiSprite.spriteFrame = this.imgs[aiRandom]
    }
    update(deltaTime: number) {
        
    }
}

